package com.jinyi.wwdeng.ui.config.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import com.jinyi.base.base.BaseActivity
import com.jinyi.base.base.BaseApplication
import com.jinyi.base.base.BaseFragment
import com.jinyi.base.utils.HHLog
import com.jinyi.wwdeng.databinding.FragmentIdCardBinding
import com.jinyi.wwdeng.ui.config.act.IdCardCameraAct
import com.jinyi.wwdeng.ui.config.act.IdCardCropAct
import com.jinyi.wwdeng.ui.config.act.IdCardCropAct.Companion.KEY_CONTENT_TYPE
import com.jinyi.wwdeng.ui.config.act.IdCardCropAct.Companion.KEY_FILE_PATH
import com.jinyi.wwdeng.utils.dialog.PhotoDialog
import java.io.File


/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/19 18:22
 * @Annotation：身份证信息
 */
class IDCardFragment: BaseFragment() {

    lateinit var binding: FragmentIdCardBinding

    private val PERMISSIONS_EXTERNAL_STORAGE = 801
    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentIdCardBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
    }

    override fun initListener() {
        //身份证正面
        binding.frontLayout.setOnClickListener {
            showPhotoDialog()
        }

        //身份证反面
        binding.backLayout.setOnClickListener {
            showPhotoDialog()
        }
    }

    override fun initData() {
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
            }
        }
    }

    /**
     * 相册选择照片
     */
    private val openAlbumResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val uri = result.data!!.data
                val imgPath = getRealPathFromURI(uri!!)
                HHLog.e("文件路径>>>>>>>>>>>>>>$imgPath")
                val intent = Intent(context,IdCardCropAct::class.java)
                val bundle = Bundle()
                bundle.putInt(KEY_CONTENT_TYPE,2)//1相机  2相册
                bundle.putString(KEY_FILE_PATH,imgPath)
                intent.putExtras(bundle)
                openCropResultLauncher.launch(intent)
//                onIntent(IdCardCropAct::class.java,bundle)
            }
        }
    }

    /**
     * 图片剪裁
     */
    private val openCropResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                HHLog.e("相册选择后剪裁返回，不需要操作")

            }
        }
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(){
        val photoDialog = PhotoDialog(context,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                onOpenCamera()
            }
            override fun openAlbum() {
                onOpenAlbum()
            }
        })
        photoDialog.setCancelable(true)
        photoDialog.setCanceledOnTouchOutside(false)
        photoDialog.show()
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
        val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
//        val intent = Intent(context, CameraActivity2::class.java)
        val intent = Intent(context, IdCardCameraAct::class.java)
        intent.putExtra(IdCardCameraAct.KEY_OUTPUT_FILE_PATH, outputFile.absolutePath)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        if (ActivityCompat.checkSelfPermission(BaseApplication.app, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ActivityCompat.requestPermissions(context as BaseActivity, arrayOf<String>(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSIONS_EXTERNAL_STORAGE)
                return
            }
        }
        val intent = Intent(Intent.ACTION_PICK)
        intent.setType("image/*")
        openAlbumResultLauncher.launch(intent)
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }
}